package com.hsmw.api.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hsmw.api.exception.ApiException;
import com.hsmw.api.mapper.*;
import com.hsmw.domain.vo.DriverDetailVO;
import com.hsmw.domain.vo.ReportWeekCount;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.TPSPUserTypeEnum;
import com.htn.common.core.enums.ReportExamineTypeEnum;
import com.hsmw.domain.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.MonthDay;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.SUCCESS;
import static java.util.stream.Collectors.toList;

@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwTpspUserService extends BaseService<HsmwTpspUserMapper, HsmwTpspUser> {

    @Autowired
    private HsmwTpspUserMapper hsmwTpspUserMapper;

    @Autowired
    private HsmwReportMapper hsmwReportMapper;

    @Autowired
    private HsmwDriverComplaintsMapper hsmwDriverComplaintsMapper;



    public HsmwTpspUser findByUsername(String username) {
        QueryWrapper<HsmwTpspUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HsmwTpspUser::getUsername, username);
        return hsmwTpspUserMapper.selectOne(queryWrapper);
    }

    /**
     * list分页
     *
     * @param page
     * @param hsmwUser
     * @return
     */
    public IPage<HsmwTpspUser> getHsmwUserPage(IPage page, HsmwTpspUser hsmwUser) {
        LambdaQueryWrapper<HsmwTpspUser> queryWrapper = new LambdaQueryWrapper<>();
        hsmwUser.setType(TPSPUserTypeEnum.TPSP.getValue());
        if (!StrUtil.isBlank(hsmwUser.getName())) {
            queryWrapper.like(HsmwUser::getName, hsmwUser.getName());
        }
        if (!StrUtil.isBlank(hsmwUser.getUsername())) {
            queryWrapper.eq(HsmwUser::getUsername, hsmwUser.getUsername());
        }
        if (!StrUtil.isBlank(hsmwUser.getType())) {
            queryWrapper.eq(HsmwUser::getType, hsmwUser.getType());
        }
        if (!StrUtil.isBlank(hsmwUser.getItemId())) {
            queryWrapper.eq(HsmwUser::getItemId, hsmwUser.getItemId());
        }
        if (!StrUtil.isBlank(hsmwUser.getConstructionUnitId())) {
            String constructionUnitId = hsmwUser.getConstructionUnitId();
            queryWrapper.eq(HsmwUser::getConstructionUnitId, constructionUnitId);
        }
        IPage ipage = this.baseMapper.selectPage(page, queryWrapper.orderByDesc(HsmwTpspUser::getCreateTime));

        List<HsmwTpspUser> records = ipage.getRecords();
        if(CollectionUtil.isNotEmpty(records)){
            records.stream().forEach(hsmwTpspUser -> {
                if(com.htn.common.core.utils.StringUtils.isNotBlank(hsmwTpspUser.getOwnCompanyId())){
                    Integer waitCount = hsmwReportMapper.selectCount(new LambdaQueryWrapper<HsmwReport>()
                            .eq(HsmwReport::getCompanyId, hsmwTpspUser.getOwnCompanyId())
                            .eq(HsmwReport::getExamineType, ReportExamineTypeEnum.WAITINGRESOLVED.getValue()));
                    Integer startCount = hsmwReportMapper.selectCount(new LambdaQueryWrapper<HsmwReport>()
                            .eq(HsmwReport::getCompanyId, hsmwTpspUser.getOwnCompanyId())
                            .eq(HsmwReport::getExamineType, ReportExamineTypeEnum.RESOLVING.getValue()));
                    Integer alreadyCount = hsmwReportMapper.selectCount(new LambdaQueryWrapper<HsmwReport>()
                            .eq(HsmwReport::getCompanyId, hsmwTpspUser.getOwnCompanyId())
                            .in(HsmwReport::getExamineType, ReportExamineTypeEnum.ALREADYRESOLVED.getValue(),ReportExamineTypeEnum.RETURNVISIT.getValue()));
                    hsmwTpspUser.setAlreadyResolved(alreadyCount);
                    hsmwTpspUser.setWaitingResolved(waitCount);
                    hsmwTpspUser.setStartResolved(startCount);
                }
            });
        }

        return ipage;
    }

    /**
     * list分页
     *
     * @param page
     * @param hsmwUser
     * @return
     */
    public IPage<HsmwTpspUser> getHsmwUserPage1(IPage page, HsmwTpspUser hsmwUser) {
        LambdaQueryWrapper<HsmwTpspUser> queryWrapper = new LambdaQueryWrapper<>();
        if (!StrUtil.isBlank(hsmwUser.getName())) {
            queryWrapper.like(HsmwUser::getName, hsmwUser.getName());
        }
        if (!StrUtil.isBlank(hsmwUser.getUsername())) {
            queryWrapper.eq(HsmwUser::getUsername, hsmwUser.getUsername());
        }
        if (!StrUtil.isBlank(hsmwUser.getType())) {
            queryWrapper.eq(HsmwUser::getType, hsmwUser.getType());
        }
        if (!StrUtil.isBlank(hsmwUser.getItemId())) {
            queryWrapper.eq(HsmwUser::getItemId, hsmwUser.getItemId());
        }
        if (!StrUtil.isBlank(hsmwUser.getConstructionUnitId())) {
            String constructionUnitId = hsmwUser.getConstructionUnitId();
            queryWrapper.eq(HsmwUser::getConstructionUnitId, constructionUnitId);
        }
        IPage ipage = this.baseMapper.selectPage(page, queryWrapper.orderByDesc(HsmwTpspUser::getCreateTime));
        //List<>

        return ipage;
    }

    /**
     * 新增或修改 逻辑删除
     *
     * @return
     */
    public DataResponse saveOrUpdateHsmwUser(HsmwTpspUser hsmwUser) {
        if (StringUtils.isNotBlank(hsmwUser.getId())) {
            LambdaQueryWrapper<HsmwTpspUser> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(HsmwTpspUser::getUsername, hsmwUser.getUsername());
            HsmwTpspUser existHsmwUser = hsmwTpspUserMapper.selectOne(lambdaQueryWrapper);
            if (existHsmwUser != null && !Objects.equals(existHsmwUser.getId(), hsmwUser.getId())) {
                throw new ApiException(CommonConstants.ResponseStatus.USER_IS_EXIST);
            } else {
                if(hsmwUser.isFlag()){
                    hsmwUser.setUsername("该账号已经删除！");
                    hsmwUser.setType(TPSPUserTypeEnum.VISITOR.getValue());
                }
                hsmwTpspUserMapper.updateById(hsmwUser);
            }
        } else {
            LambdaQueryWrapper<HsmwTpspUser> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(HsmwTpspUser::getUsername, hsmwUser.getUsername());
            HsmwUser existHsmwUser = hsmwTpspUserMapper.selectOne(lambdaQueryWrapper);
            if (existHsmwUser == null) {
                hsmwUser.setEnabled(true);
                hsmwUser.setFlag(false);
                hsmwUser.setType(TPSPUserTypeEnum.TPSP.getValue());
                hsmwTpspUserMapper.insert(hsmwUser);
            } else {
                throw new ApiException(CommonConstants.ResponseStatus.USER_IS_EXIST);
            }
        }
        return new DataResponse(SUCCESS);
    }

    public HsmwUser getTpspDetailById(String key,String type) {
        HsmwTpspUser hsmwTpspUser = hsmwTpspUserMapper.selectById(key);
        Integer satisfyCount = hsmwDriverComplaintsMapper.selectCount(new LambdaQueryWrapper<HsmwDriverComplaints>()
                .eq(HsmwDriverComplaints::getSatisfied,CommonConstants.YES)
                .eq(HsmwDriverComplaints::getSupplierId,hsmwTpspUser.getId()));

        Integer unSatisfyCount = hsmwDriverComplaintsMapper.selectCount(new LambdaQueryWrapper<HsmwDriverComplaints>()
                .eq(HsmwDriverComplaints::getSatisfied,CommonConstants.NO)
                .eq(HsmwDriverComplaints::getSupplierId,hsmwTpspUser.getId()));

        HashMap param = new HashMap();
        String companyId = hsmwTpspUser.getOwnCompanyId();
        param.put("companyId",companyId.split(","));
        Integer UnEvaluateCount = hsmwDriverComplaintsMapper.selectUnEvaluateCount(param);

        hsmwTpspUser.setUnSatisfyCount(unSatisfyCount);
        hsmwTpspUser.setSatisfyCount(satisfyCount);
        hsmwTpspUser.setUnEvaluateCount(UnEvaluateCount);

        if("week".equals(type)){
            LocalDate listDays = LocalDate.now();
            List<LocalDate> localDates = Arrays.asList(DayOfWeek.values()).stream().map(listDays::with).collect(toList());
            String startTime = localDates.get(0).toString();
            String  endTime = localDates.get(6).plusDays(1).toString();
            param.put("startTime",startTime);
            param.put("endTime",endTime);
            List<ReportWeekCount> weekCounts = hsmwDriverComplaintsMapper.selectWeekData(param);
            if(CollectionUtil.isNotEmpty(weekCounts)){
                weekCounts.stream().forEach(weekCount->{
                    if(weekCount.getWeek()==1){
                        weekCount.setWeekName("星期一");
                    }
                    if(weekCount.getWeek()==2){
                        weekCount.setWeekName("星期二");

                    } if(weekCount.getWeek()==3){
                        weekCount.setWeekName("星期三");

                    } if(weekCount.getWeek()==4){
                        weekCount.setWeekName("星期四");

                    } if(weekCount.getWeek()==5){
                        weekCount.setWeekName("星期五");

                    } if(weekCount.getWeek()==6){
                        weekCount.setWeekName("星期六");

                    } if(weekCount.getWeek()==7){
                        weekCount.setWeekName("星期日");
                    }
                });
            }
            hsmwTpspUser.setWeekCounts(weekCounts);
        }else {
            LocalDate localDate =LocalDate.now();
            //这个月的第一天
            Date monthStart = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
            //这个月的最后一天 下个月的第一天
            Date monthEnd = Date.from(localDate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
            DateTime endTime = DateUtil.date(monthEnd);
            DateTime startTime = DateUtil.date(monthStart);
            param.put("startTime",startTime);
            param.put("endTime",endTime);
            List<ReportWeekCount> monthCounts = hsmwDriverComplaintsMapper.selectMonthData(param);
            hsmwTpspUser.setMonthCounts(monthCounts);
            List<String> dayBetween =com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(endTime.toJdkDate(), "yyyy-MM-dd"));
            dayBetween.remove(dayBetween.size()-1);
            hsmwTpspUser.setDayBetween(dayBetween);

        }

        Integer alreadyCount = hsmwReportMapper.selectCount(new LambdaQueryWrapper<HsmwReport>()
                .eq(HsmwReport::getCompanyId, hsmwTpspUser.getOwnCompanyId())
                .in(HsmwReport::getExamineType, ReportExamineTypeEnum.ALREADYRESOLVED.getValue(),ReportExamineTypeEnum.RETURNVISIT.getValue()));
        hsmwTpspUser.setAlreadyResolved(alreadyCount);
        return hsmwTpspUser;
    }


    public static void main(String[] args) {

    }
}
